package com.changestuffs.commons.chain;

import com.google.common.eventbus.EventBus;


public class ChainProccessor {

	private final EventBus eventBus = new EventBus();
	private AbstractChain first;
	
	public ChainProccessor(AbstractChain ... chain){
		if(chain == null || chain.length == 0)
			throw new RuntimeException("Chain is null or its size is 0");
		AbstractChain lastElement = null;
		for(AbstractChain element : chain){
			if(element instanceof AbstractSubscribedChain){
				eventBus.register(element);
			}
			element.setEventBus(eventBus);
			if(first == null){
				first = element;
				lastElement = first;
			}else{
				fillChain(lastElement, element);
				lastElement = element;
			}
		}
	}
	
	private void fillChain(AbstractChain previusElement, AbstractChain nextElement){
		previusElement.setNext(nextElement);
	}
	
	public void start(){
		first.execute();
	}
	
}
